import 'package:flutter/material.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:wuxu_flutter_lianxi/dao/UserDao.dart';
import 'package:wuxu_flutter_lianxi/page/login/login_page.dart';
import 'package:wuxu_flutter_lianxi/page/main/main_page.dart';
import 'package:wuxu_flutter_lianxi/page/splash/splash.dart';
import 'package:wuxu_flutter_lianxi/redux/wx_state.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'package:wuxu_flutter_lianxi/route/route_paths.dart';
import 'package:wuxu_flutter_lianxi/style/wx_style.dart';

import 'localization/default_localizations.dart';

///
/// 整个应用的入口
///
/// redux 用于全局的状态管理，与Provider搭配使用，可以将数据及变化通知传给子组件。
///
/// 个人理解：
///        redux 等同于状态机，且会将变化通知出去
///        StoreProvider继承自InheritedWidget，是flutter中的一个共享部件
///        二者搭配，可以将状态机传递给子组件，子组件可以根据收到的通知进行view的刷新
///
/// 补充理解：我还认为，redux的设计与MVI架构模式二者一样。Reducer即缓冲器，进行数据的处理设置，生产出新的状态。状态变化引起UI变化。
///
/// redux 核心：Store、
///
///
class WXApp extends StatefulWidget {
  const WXApp({super.key});

  @override
  State<StatefulWidget> createState() => _WXAppState();
}

class _WXAppState extends State<WXApp> {
  final store = Store<WXState>(createReducer, initialState: WXState(
    userInfo: UserDao.getUserInfo()
  ),middleware: wxMiddleware);

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return StoreProvider(
        store: store,
        child: StoreBuilder<WXState>(builder: (context, store) {
          ///使用 StoreBuilder 获取 store 中的 theme 、locale
          store.state.platformLocale =
              WidgetsBinding.instance.platformDispatcher.locale;
          store.state.locale =
              WidgetsBinding.instance.platformDispatcher.locale;
          Widget app = MaterialApp(
              //不能用const标记，因为内部有运行时才会明确的数据
              theme: ThemeData(primaryColor: WxColors.primaryValue),
              //多语言委托代理
              localizationsDelegates: [
                GlobalMaterialLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,

                //这个是应用真正的语言代理类，上面是系统自带的
                //这个代理，就是将 WxLocalizations绑在了根部件上
                WxLocalizationsDelegate.delegate
              ],
              supportedLocales: [
                store.state.locale ?? store.state.platformLocale!
              ],

              locale: store.state.locale, //设定当前语言，default_localization里会使用这个字段
              //使用命名路由
              routes: {
                //welcome == "/"  表示默认路由
                pageWelcome: (context) => SplashWidget(),
                pageMain: (context) {
                  return MainPage();
                },

                pageLogin: (context) {
                  return LoginPage();
                },
              });
          return app;
        }));
  }
}
